'use strict';

const Controller = require('egg').Controller;
const fs = require('fs')
const path = require('path')
const pump = require('pump')

class MainController extends Controller {
  async index() {
    this.ctx.body = '这是后台接口'
  }
  // 后台登录接口
  async checkLogin() {
    let userName = this.ctx.request.body.userName;
    let password = this.ctx.request.body.password;
    const sql = `SELECT userName FROM admin_user WhERE userName = '${userName}' AND password = '${password}'`;
    const res = await this.app.mysql.query(sql);
    if (res.length > 0) {
      // 用户存在,生成token
      const token = this.app.jwt.sign({
        name: res[0].userName,
      }, this.app.config.jwt.secret);
      this.ctx.body = { 'data': '登录成功', 'token': token };
    } else {
      this.ctx.body = { 'data': '登录失败' };
    }
  }
  // 获取文章类型
  async getTypeInfo() {
    const resType = await this.app.mysql.select('type');
    this.ctx.body = { data: resType };
  }
  // 添加文章
  async addArticle() {
    let tmpArticle = this.ctx.request.body;
    const result = await this.app.mysql.insert('article', tmpArticle);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;
    this.ctx.body = {
      isSuccess: insertSuccess,
      insertId: insertId
    }
  }
  // 更新文章
  async updateArticle() {
    let tmpArticle = this.ctx.request.body;
    const result = await this.app.mysql.update('article', tmpArticle);
    const updateSuccess = result.affectedRows === 1;
    this.ctx.body = {
      isSuccess: updateSuccess,
    }
  }
  // 添加随笔
  async addEssay() {
    let tmpArticle = this.ctx.request.body;
    console.log(tmpArticle);
    const result = await this.app.mysql.insert('essay', tmpArticle);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;
    this.ctx.body = {
      isSuccess: insertSuccess,
      insertId: insertId
    }
  }
  // 更新随笔
  async updateEssay() {
    let tmpArticle = this.ctx.request.body;
    const result = await this.app.mysql.update('essay', tmpArticle);
    const updateSuccess = result.affectedRows === 1;
    this.ctx.body = {
      isSuccess: updateSuccess,
    }
  }
  // 获取文章列表
  async getArticleList() {
    let sql = `SELECT 
    article.id as id,
    article.title as title,
    article.introduce as introduce,
    FROM_UNIXTIME(article.addTime,'%Y-%m-%d') as addTime,
    article.view_count as view_count,
    type.typeName as typeName
    FROM article LEFT JOIN type ON article.type_id = type.id ORDER BY article.id DESC`;
    const results = await this.app.mysql.query(sql);
    this.ctx.body = { data: results };
  }
  // 删除文章
  async delArticle() {
    let id = this.ctx.query.id;
    const res = await this.app.mysql.delete('article', { id: id });
    this.ctx.body = { data: res };
  }
  // 修改文章
  async getArticleById() {
    let id = this.ctx.query.id;
    let sql = `SELECT 
    article.id as id,
    article.title as title,
    article.introduce as introduce,
    FROM_UNIXTIME(article.addTime,'%Y-%m-%d') as addTime,
    article.view_count as view_count,
    article.article_url as article_url,
    article.article_content as article_content,
    type.typeName as typeName,
    type.id as typeId
    FROM article LEFT JOIN type ON article.type_id = type.id WHERE article.id = ${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  // 文章图片上传
  async saveUploadImg() {
    const { ctx } = this;
    const parts = ctx.multipart({ autoFields: true });
    let files = {};
    let stream;
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        break;
      }
      const fieldname = stream.fieldname; // file表单的名字
      const dir = await this.service.tools.getUploadFile(stream.filename);
      const target = dir.uploadDir;
      const writeStream = fs.createWriteStream(target);
      await pump(stream, writeStream);
      files = Object.assign(files, {
        [fieldname]: dir.saveDir,
      });
    }
    if (Object.keys(files).length > 0) {
      ctx.body = {
        code: 200,
        message: '图片上传成功',
        data: files,
      }
    } else {
      ctx.body = {
        code: 500,
        message: '图片上传失败',
        data: {}
      }
    }
  }
  // 随心笔记图片上传
  async saveEssayImg() {
    const { ctx } = this;
    const parts = ctx.multipart({ autoFields: true });
    let files = {};
    let stream;
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        break;
      }
      const fieldname = stream.fieldname; // file表单的名字
      const dir = await this.service.essay.getUploadFile(stream.filename);
      const target = dir.uploadDir;
      const writeStream = fs.createWriteStream(target);
      await pump(stream, writeStream);
      files = Object.assign(files, {
        [fieldname]: dir.saveDir,
      });
    }
    if (Object.keys(files).length > 0) {
      ctx.body = {
        code: 200,
        message: '图片上传成功',
        data: files,
      }
    } else {
      ctx.body = {
        code: 500,
        message: '图片上传失败',
        data: {}
      }
    }
  }
  // 获取随笔列表
  async getEssayList() {
    let data = this.ctx.query;
    let total = await this.app.mysql.query('SELECT COUNT(*) total FROM essay');
    let sql = `SELECT 
    essay.id as id,
    essay.content as content,
    FROM_UNIXTIME(essay.addTime,'%Y-%m-%d %H:%i:%S') as addTime,
    essay.essay_url as essay_url
    FROM essay ORDER BY essay.addTime DESC limit ${(data.current - 1) * data.pageSize},${data.pageSize}`;
    const results = await this.app.mysql.query(sql);
    this.ctx.body = { data: results, total: total[0].total };
  }
  // 删除随笔
  async delEssay() {
    let id = this.ctx.query.id;
    const res = await this.app.mysql.delete('essay', { id: id });
    this.ctx.body = { data: res, status: 200 };
  }
  // 获取留言列表
  async getMessageList() {
    let sql = `SELECT 
    id,
    nickName,
    content,
    email,
    status,
    FROM_UNIXTIME(addTime,'%Y-%m-%d %H:%i:%S') as addTime
    FROM message ORDER BY addTime DESC`;
    const results = await this.app.mysql.query(sql);
    results.forEach(element => {
      element.status = element.status == 1 ? true : false;
    });
    this.ctx.body = { data: results };
  }
  async updateMessageStatus() {
    let { id, status } = this.ctx.request.body;
    let result = await this.app.mysql.update('message', { id: id, status: status });
    if (result) {
      this.ctx.body = {
        data: {
          msg: '留言更新成功',
          status: 200
        }
      }
    }
  }
}
module.exports = MainController;
